﻿using HCQ2_Common;
using HCQ2_IBLL;
using HCQ2_Model;
using HCQ2_Model.APIBase;
using HCQ2_Model.VLine.InputDto._20220219;
using HCQ2_Model.VLine.OutputDto._20220219;
using HCQ2_Model.VRDD.InputDto._210908;
using HCQ2_Model.VRDD.OutputDto._210908;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;


namespace HCQ2_BLL
{
    public partial class T_VRDDStoreDynamicBLL: IT_VRDDStoreDynamicBLL
    {
        /// <summary>
        ///  获取店铺动态列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public BasePage<GetStoreNewsOutput> GetStoreNews(GetStoreNewsInput param)
        {
            int total;
            var list = DBSession.IT_VRDDStoreDynamicDAL.GetStoreNews(param,out total);
            list?.ForEach(s =>
            {
                //商品缩略图
                if (s.fileID > 0)
                {
                    //1、缩略图列表
                    List<T_DocBagFileRecord> fileImage = DBSession.IT_DocBagFileRecordDAL.Select(o => o.file_id == s.fileID);
                    if (fileImage.Count > 0)
                        fileImage.ForEach(o => o.file_url = o.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                    s.fileImage = fileImage;
                }
            });
            return new BasePage<GetStoreNewsOutput> { total = total, rows = list };
        }
        /// <summary>
        ///  获取有动态的年-月
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<NewsDateOutput> GetNewsDate(NewsDateInput param)
        {
            List<NewsDateOutput> list = new List<NewsDateOutput>();
            var result = DBSession.IT_VRDDStoreDynamicDAL.GetNewsDate(param);
            List<int> lyears = result.Select(s => s.year).ToList();
            //排除年份重复
            HashSet<int> set = new HashSet<int>(lyears);
            //循环年份
            foreach(var item in set)
            {
                NewsDateOutput year = new NewsDateOutput { Year = item };
                List<MonthList> monthList = new List<MonthList>();
                var temp = result.Where(s => s.year == item)?.ToList();
                //循环月份
                temp?.ForEach(o =>
                {
                    string m = o.create_date.Split('-')[1];
                    if (m.Substring(0, 1).Equals("0"))
                        m = m.Substring(1);
                    monthList.Add(new MonthList
                    {
                        Month = Helper.ToInt(m)
                    });
                });
                year.MonthList = monthList;
                list.Add(year);
            }
            return list;
        }
        /// <summary>
        ///  获取好友店铺动态
        /// </summary>
        /// <param name="param">参数</param>
        /// <param name="user_id">登录用户id</param>
        /// <returns></returns>
        public BasePage<FriendStoreNewsOutput> GetFriendStoreNews(FriendStoreNewsInput param, int user_id,int owenid)
        {
            BasePage<FriendStoreNewsOutput> result = new BasePage<FriendStoreNewsOutput>();
            int total;
            //获取好友、自己+推荐
            var list = DBSession.IT_VRDDStoreDynamicDAL.GetFriendStoreNews(param, user_id, out total,owenid);
            list?.ForEach(s => {
                //店铺logo
                if(!string.IsNullOrEmpty(s.folderUrl))
                    s.folderUrl = s.folderUrl.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                //店主用户头像
                if (!string.IsNullOrEmpty(s.ownerImg))
                    s.ownerImg = s.ownerImg.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                //处理店铺角色列表
                if (!string.IsNullOrEmpty(s.store_type))
                    s.roleList = new List<string>(s.store_type.Split(','));
                //商品缩略图
                if (s.fileID > 0)
                {
                    //1、缩略图列表
                    List<T_DocBagFileRecord> fileImage = DBSession.IT_DocBagFileRecordDAL.Select(o => o.file_id == s.fileID);
                    if (fileImage.Count > 0)
                        fileImage.ForEach(o => o.file_url = o.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                    s.fileImage = fileImage;
                }
                //处理合伙人状态
                if (user_id == s.owner_id)
                    s.partnerStatus = 100;
                else
                {
                    var apply = DBSession.IT_VRFounderApplyDAL.FindSingle(o => o.folder_id == s.folderID && o.user_id == user_id);
                    if (apply == null)
                        s.partnerStatus = -1;
                    else
                        s.partnerStatus = apply.apply_status;
                }
                //商品列表
                if (param.fileListNum > 0)
                {
                    var file = DBSession.IT_DocumentFolderDAL.GetGoodsByFolders(s.folderPath, param.fileListNum);
                    file?.ForEach(o => {
                        if (!string.IsNullOrEmpty(o.fileImage))
                            o.fileImage = o.fileImage?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    });
                    s.fileList = file;
                }
            });
            result.total = total;
            result.rows = list;
            return result;
        }
        /// <summary>
        ///  保存用户动态推荐
        /// </summary>
        /// <param name="dy_id"></param>
        /// <param name="folder_id"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public bool SavePushUserData(int dy_id,int folder_id, int user_id,string userid)
        {
            int day = 0, week = 0;
            string limet = DBSession.IT_VRDDStoreDynamicDAL.GetVideosFeedNumber("VideosFeedNumber", user_id);
            //为空表示不做推荐
            if (string.IsNullOrEmpty(limet) || limet.IndexOf('/') < 0)
                return false;
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            //判断当天推荐数量是否达到上线
            string[] temp = limet.Split('/');
            day = Helper.ToInt(temp[0]);
            week = Helper.ToInt(temp[1]);
            //获取陌生人数量
            int pushNum = DBSession.IT_VRDDStoreDynamicDAL.GetStrangerNumber(user_id, folder_id);
            if (pushNum <= 0)
                return true;
            int sendNum = pushNum;//写入被推荐人数量
            //推荐主表
            var dy = DBSession.IT_VRDDStoreDynamicUserDAL.FindSingle(s => s.user_id == user_id);
            if (dy != null)
            {
                //根据推送时间计算星期天所属日期
                var sundayDate = GetSundayDate(dy.pushDate);
                //判断是否在本周内【周一至周日】
                if (DateTime.Now > sundayDate)
                {
                    #region 垮周【相当于首次推荐】
                    if (sendNum > day && day > 0)
                        sendNum = day;
                    //写入被推荐人
                    int p = DBSession.IT_VRDDStoreDynamicDAL.InsertBeStrangerUser(dy_id, user_id, folder_id, sendNum);
                    if (p > 0)
                    {
                        //写入推荐限流主表
                        DBSession.IT_VRDDStoreDynamicUserDAL.Modify(new T_VRDDStoreDynamicUser
                        {
                            numDay = sendNum,
                            numWeek = sendNum,
                            pushDate = DateTime.Now
                        }, s => s.specID == dy.specID, "numDay", "numWeek", "pushDate");
                    }
                    #endregion
                }
                else
                {
                    #region 本周内
                    //有数据、判断当前是否已超
                    if ((dy.numDay < day || day == 0) && (dy.numWeek < week || week == 0))
                    {
                        int d = dy.numDay + pushNum,//当前推荐后的数据量
                            w = dy.numWeek + pushNum;//当前推荐后本周的总数
                        if (d > day && day > 0)
                            sendNum = day - dy.numDay;
                        if (w > week && week > 0)
                            sendNum = week - dy.numWeek;
                        //写入被推荐人
                        int p = DBSession.IT_VRDDStoreDynamicDAL.InsertBeStrangerUser(dy_id, user_id, folder_id, sendNum);
                        if (p > 0)
                        {
                            //更新推荐限流表【当天】
                            if (dy.pushDate.ToString("yyyy-MM-dd").Equals(date))
                                //当天更新
                                dy.numDay = dy.numDay + sendNum;
                            else
                            {
                                //隔天【一天或多天】
                                dy.pushDate = DateTime.Now;
                                dy.numDay = sendNum;
                            }
                            dy.numWeek = dy.numWeek + sendNum;
                            //更新推荐限流主表
                            DBSession.IT_VRDDStoreDynamicUserDAL.Modify(dy, s => s.specID == dy.specID, "numDay", "numWeek", "pushDate");
                        }
                    }
                    #endregion
                }
            }
            else
            {
                #region 首次推荐
                if (day > 0 && pushNum > day)
                    sendNum = day;
                //写入被推荐人
                int p = DBSession.IT_VRDDStoreDynamicDAL.InsertBeStrangerUser(dy_id, user_id, folder_id, sendNum);
                if (p > 0)
                {
                    //写入推荐限流主表
                    DBSession.IT_VRDDStoreDynamicUserDAL.Add(new T_VRDDStoreDynamicUser
                    {
                        userid = userid,
                        user_id = user_id,
                        numDay = sendNum,
                        numWeek = sendNum,
                        pushDate = DateTime.Now
                    });
                }
                #endregion
            }
            return true;
        }
        /// <summary>
        ///  根据当前日期推算本周星期天日期
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DateTime GetSundayDate(DateTime dt)
        {
            int addDay = 0;
            switch (dt.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    addDay = 6;
                    break;
                case DayOfWeek.Tuesday:
                    addDay = 5;
                    break;
                case DayOfWeek.Wednesday:
                    addDay = 4;
                    break;
                case DayOfWeek.Thursday:
                    addDay = 3;
                    break;
                case DayOfWeek.Friday:
                    addDay = 2;
                    break;
                case DayOfWeek.Saturday:
                    addDay = 1;
                    break;
                case DayOfWeek.Sunday:
                    addDay = 0;
                    break;
            }
            return dt.AddDays(addDay);
        }
    }
}